# -*-coding:utf-8-*-

import aiohttp
import asyncio
from inspect import isfunction
import time
import logger


# @logging_utils.exception(logger)
def request(pool, data_list):
    # def request(method, url, data, headers, callback):
    loop = asyncio.get_event_loop()
    loop.run_until_complete(exec(pool, data_list))
    # loop.run_until_complete(fetch(method, url, data, headers, callback))


async def exec(pool, data_list):
    tasks = []
    sem = asyncio.Semaphore(pool)
    for item in data_list:
        tasks.append(
            control_sem(sem,
                        item.get("method", "GET"),
                        item.get("url"),
                        item.get("data"),
                        item.get("headers"),
                        item.get("callback")))
    await asyncio.wait(tasks)


async def control_sem(sem, method, url, data, headers, callback):
    async with sem:
        count = 0
        flag = False
        while not flag and count < 4:
            flag = await fetch(method, url, data, headers, callback)
            count = count + 1
            print("flag:{},count:{}".format(flag, count))
        if count == 4 and not flag:
            raise Exception('EAS service not responding after 4 times of retry.')


async def fetch(method, url, data, headers, callback):
    async with aiohttp.request(method, url=url, data=data, headers=headers) as resp:
        try:
            json = await resp.read()
            print(json)
            if resp.status != 200:
                return False
            if isfunction(callback):
                callback(json)
            return True
        except Exception as e:
            print(e)


if __name__ == '__main__':
    #  item.get("method", "GET"),
    #                         item.get("url"),
    #                         item.get("data"),
    #                         item.get("headers"),
    #                         item.get("callback")
    data = [{
        "url": "http://127.0.0.1:8000/users/login/?next=/",
        "data": "",
        "headers": None,
        "callback": "",
        "method": None
    }, ]
    request(pool=5, data_list=data)
